# @File    : cancel_ota.py
# @Project : Airtest_JBL_IOS
import re
from exception.custom_exception import ElectricException
from iOS.normal_ota import NormalOta
from airtest.core.api import *
import logging
from common.logUtil import info_i, warning_i
logging.getLogger("airtest").setLevel(logging.CRITICAL)


# 取消升级
"""取消升级后会回到首页， 会保存下载进度"""


class CancelOta(NormalOta):

    h_version = NormalOta.location.read_yaml()['h_version']
    l_version = NormalOta.location.read_yaml()['l_version']
    s_h_version = NormalOta.location.read_yaml()['s_h_version']
    s_l_version = NormalOta.location.read_yaml()['s_l_version']
    test_device = NormalOta.location.read_yaml()['device']

    process = ".*%"

    def cancel_ota(self, num):
        self.check_is_local_ota()
        version = self.check_version()
        i = 1
        while i < int(num) + 1:
            try:
                if version == self.l_version:
                    if i == 1:
                        self.select_version(version, self.test_device)
                    self.start_ota(version)
                    self.check_upgrade(i)
                    if self.test_device == "耳机":
                        version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                    else:
                        version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                    if version == self.h_version:
                        i -= 1
                elif version == self.h_version:
                    self.is_height(i, version)
                    i -= 1
                else:
                    i -= 1
                i += 1
            except ElectricException:
                self.fail_num += 1
                self.fail_list.append(i)
                warning_i(f"第 {i} 次升级时耳机电量过低，无法升级!")
                break
            except TargetNotFoundError:
                self.fail_num += 1
                self.fail_list.append(i)
                warning_i("出现异常了，请手动跟换安装包或者出现运行程序")
                break
        sleep(2)
        info_i(
            f"测试完成, 共压测 {i - 1} 次, 其中 PASS {self.pass_num} 次, FAIL {self.fail_num} 次, FAIL的轮数为{self.fail_list}")
        self.fail_list.clear()

    def is_height(self, i, version):
        self.select_version(version, self.test_device)
        self.start_ota(version)
        self.ota_process(i, version)
        sleep(1)

    def start_ota(self, version):
        if self.test_device == "耳机":
            self.poco("软件").click()
        else:
            self.poco("智能保护盒").click()
        self.poco("更新").refresh()
        self.poco("更新").click()
        if version == self.h_version:
            info_i("开始降级...")
        elif version == self.l_version:
            info_i("开始升级...")

    def ota_process(self, i, version):
        while True:

            if self.poco("耳机电量需超过 50%。").exists():
                raise ElectricException
            if not self.poco(nameMatches=f"{self.schedule}").exists():
                if self.poco("更新成功").exists():
                    self.poco("完成").click()
                    if self.test_device == "耳机":
                        version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                    else:
                        version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                    self.check_after_version(i, version)
                    break
                # 更新失败处理
                elif self.poco("更新失败").exists():
                    self.poco("取消").click()
                    sleep(2)
                    # version = self.ex.check_fail()
                    self.check_after_version(i, version)
                    self.fail_num += 1
                    self.fail_list.append(i)
                    break
            if self.poco("重试").exists():
                warning_i("请将充电盒靠近手机后重试")
                self.poco("重试").click()
                sleep(1)
                self.poco("更新").click()

    def check_upgrade(self, i):
        while True:
            if self.poco("耳机电量需超过 50%。").exists():
                raise ElectricException
            if self.poco(nameMatches=f"{self.schedule}").exists():
                result = self.is_install(self.poco(nameMatches=f"{self.process}").get_name())
                if result:
                    while True:
                        if self.poco("更新成功").exists():
                            self.poco("完成").click()
                            if self.test_device == "耳机":
                                version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                            else:
                                version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                            info_i(f"当前耳机版本为:{version}")
                            break
                        # 更新失败处理
                        elif self.poco("更新失败").exists():
                            self.poco("取消").click()
                            sleep(2)
                            # version = self.ex.check_fail()
                            self.fail_num += 1
                            self.fail_list.append(i)
                            break
                    break
                else:
                    sleep(2)
                    self.poco("取消").click()
                    self.poco("退出").click()
                    other = self.poco("Others").wait(15)
                    if other.exists():
                        other.click()
                        swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
                        self.poco("支持").click()
                        if self.test_device == "耳机":
                            version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                        else:
                            version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                        self.check_result(i, version)
                        break

    # 取消升级输出测试结果
    def check_after_version(self, i, version):
        if version == self.h_version:
            info_i(f"升级成功...")
            sleep(1)
            info_i(f"升级后的版本为: {version}")
        elif version == self.l_version:
            info_i(f"降级成功...")
            sleep(1)
            info_i(f"降级后的版本为: {version}")

    def check_result(self, i, version):
        if version == self.l_version:
            info_i(f"第 {i} 次取消升级后的版本为: {version}")
            sleep(1)
            info_i(f"第 {i} 次测试结果为PASS")
            self.pass_num += 1
        else:
            warning_i(f"第 {i} 次取消升级后的版本为: {version}")
            sleep(1)
            warning_i(f"第 {i} 次测试结果为FAIL")
            self.fail_num += 1
            self.fail_list.append(i)

    # 检查当前下载进度(如果当前下载进度大于等于96%，则不点击取消，等待升级完成)
    def is_install(self, t):
        pattern = "^9[5-9]%"
        if re.match(pattern, t):
            return True
        else:
            return False
